package timing.ukulele.form.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.form.persistent.FormTemplateHistory;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.ResultCode;
import timing.ukulele.common.form.FormTemplateData;
import timing.ukulele.common.item.ItemData;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.form.client.ItemClient;
import timing.ukulele.form.client.SystemClient;
import timing.ukulele.form.mapper.FromTemplateMapper;
import timing.ukulele.form.persistent.FormTemplate;
import timing.ukulele.persistent.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class FormTemplateService extends BaseService<FromTemplateMapper, FormTemplate> {

    @Resource
    private SystemClient systemClient;
    @Resource
    private ItemClient itemClient;

    private final FormTemplateHistoryService formTemplateHistoryService;

    public FormTemplateService(FormTemplateHistoryService formTemplateHistoryService) {
        this.formTemplateHistoryService = formTemplateHistoryService;
    }

    /**
     * 获取分页
     *
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<FormTemplate> getPage(String system, int current, int size, HashMap<String, Object> map) {
        Page<FormTemplate> page = new Page<>(current, size);
        LambdaQueryWrapper<FormTemplate> qw = new LambdaQueryWrapper<>();
        if (map.get("name") != null) {
            qw.like(FormTemplate::getName, map.get("name"));
        }
        if (map.get("code") != null) {
            qw.like(FormTemplate::getCode, map.get("code"));
        }
        List<Long> systemIds = null;
        if (!"".equals(system)) {
            String[] split = system.split(",");
            if (!"0".equals(split[0])) {
                systemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                qw.in(FormTemplate::getSystemId, systemIds);
            }
        }
        if (map.get("useId") != null) {
            qw.eq(FormTemplate::getUseId, map.get("useId"));
            qw.orderByDesc(FormTemplate::getVersion);
        } else {
            qw.eq(FormTemplate::getUseId, 0); // 查询正在使用的版本
        }
        qw.orderByDesc(FormTemplate::getId);
        //对sytemName的模糊查询
        final ResponseResult<List<SystemData>> responseResult;
        if (map.get("systemName") != null) {
            responseResult = systemClient.getLikeSystemName((String) map.get("systemName"));
        } else {
            responseResult = systemClient.all();
        }
        //获取业务系统id的集合
        List<Long> systemIdList = new ArrayList<>();
        if (responseResult.getData() != null) {
            responseResult.getData().stream().forEach(e -> systemIdList.add(e.getId()));
        }
        if (!CollectionUtils.isEmpty(systemIdList)) {
            qw.in(FormTemplate::getSystemId, systemIdList);
        }
        IPage<FormTemplate> iPage = getBaseMapper().selectPage(page, qw);
        List<FormTemplate> templates = iPage.getRecords();
        Map<Long, String> systemNameMap = null;
        if (responseResult != null && !CollectionUtils.isEmpty(responseResult.getData())) {
            systemNameMap = responseResult.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
        }
        for (FormTemplate template : templates) {
            if (!CollectionUtils.isEmpty(systemNameMap)) {
                template.setSystemName(systemNameMap.get(template.getSystemId()));
            }

        }
        return iPage;
    }

    /**
     * 获取分页
     *
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<FormTemplate> getItemFormPage(String system, Long templateId, int current, int size) {
        Page<FormTemplate> page = new Page<>(current, size);
        LambdaQueryWrapper<FormTemplate> qw = new LambdaQueryWrapper<>();
        Page<FormTemplateHistory> pageHistory = new Page<>(current, size);
        LambdaQueryWrapper<FormTemplateHistory> qwHistory = new LambdaQueryWrapper<>();
        if (templateId == null) {
            List<Long> systemIds;
            if (!"".equals(system)) {
                String[] split = system.split(",");
                if (!"0".equals(split[0])) {
                    systemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                    qw.in(FormTemplate::getSystemId, systemIds);
                }
            }
            qw.orderByDesc(FormTemplate::getId);
            final ResponseResult<List<SystemData>> responseResult = systemClient.all();
            page = getBaseMapper().selectPage(page, qw);
            List<FormTemplate> templates = page.getRecords();
            Map<Long, String> systemNameMap = null;
            if (responseResult != null && !CollectionUtils.isEmpty(responseResult.getData())) {
                systemNameMap = responseResult.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
            }
            for (FormTemplate template : templates) {
                if (!CollectionUtils.isEmpty(systemNameMap)) {
                    template.setSystemName(systemNameMap.get(template.getSystemId()));
                }

            }
            return page;
        } else {
            List<FormTemplate> templates = new ArrayList<>();
            qw.eq(FormTemplate::getId, templateId);
            FormTemplate formTemplateUse = getBaseMapper().selectOne(qw);
            if (Objects.isNull(formTemplateUse)) {
                //说明表单不是最高版本
                qwHistory.eq(FormTemplateHistory::getId, templateId);
                FormTemplateHistory formTemplateHistoryUse =
                    formTemplateHistoryService.getBaseMapper().selectOne(qwHistory);
                if (!Objects.isNull(formTemplateHistoryUse)) {
                    //还要去查最新版本的表单
                    qw.clear();
                    qw.eq(FormTemplate::getId, formTemplateHistoryUse.getUseId());
                    FormTemplate formTemplateNew = getBaseMapper().selectOne(qw);
                    templates.add(formTemplateNew);
                    templateId = formTemplateHistoryUse.getUseId();
                }
            } else {
                templates.add(formTemplateUse);
            }
            qwHistory.clear();
            qwHistory.eq(FormTemplateHistory::getUseId, templateId);
            qwHistory.orderByDesc(FormTemplateHistory::getId);
            final ResponseResult<List<SystemData>> responseResult = systemClient.all();
            pageHistory = formTemplateHistoryService.getBaseMapper().selectPage(pageHistory, qwHistory);
            List<FormTemplateHistory> templateHistories = pageHistory.getRecords();
            Map<Long, String> systemNameMap = null;
            if (responseResult != null && !CollectionUtils.isEmpty(responseResult.getData())) {
                systemNameMap = responseResult.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
            }
            for (FormTemplateHistory templateHistory : templateHistories) {
                FormTemplate formTemplate = new FormTemplate();
                BeanUtils.copyProperties(templateHistory, formTemplate);
                if (!CollectionUtils.isEmpty(systemNameMap)) {
                    formTemplate.setSystemName(systemNameMap.get(templateHistory.getSystemId()));
                }
                templates.add(formTemplate);
            }
            page.setTotal(pageHistory.getTotal());
            page.setPages(pageHistory.getPages());
            page.setRecords(templates);
            return page;
        }

    }

    public IPage<FormTemplate> getPageBySystemId(Long systemId, Integer pageNum, Integer pageSize, Integer active) {
        Page<FormTemplate> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<FormTemplate> qw = new LambdaQueryWrapper<>();
        //默认是启用
        if (active != null) {
            qw.eq(FormTemplate::getActive, active);
        } else {
            qw.eq(FormTemplate::getActive, 1);
        }
        if (systemId != null) {
            qw.eq(FormTemplate::getSystemId, systemId);
        }
        qw.orderByDesc(FormTemplate::getId);
        IPage<FormTemplate> iPage = getBaseMapper().selectPage(page, qw);
        return iPage;
    }

    /**
     * 修改表单
     *
     * @param template
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<FormTemplate> updateContent(FormTemplate template, String username) {
        FormTemplate formTemplate = getBaseMapper().selectById(template.getId());
        if (StringUtils.isEmpty(formTemplate.getContent())) {
            formTemplate.setUpdateBy(username);
            formTemplate.setContent(template.getContent());
            getBaseMapper().updateById(formTemplate);
        } else {
            FormTemplate newTemplate = new FormTemplate();
            newTemplate.setVersion(Math.max(getBaseMapper().getMaxVersion(template.getId()), formTemplateHistoryService.getBaseMapper().getMaxVersion(template.getId()) == null ? 0 : formTemplateHistoryService.getBaseMapper().getMaxVersion(template.getId())) + 1); // 获取最大版本+1
            newTemplate.setCode(formTemplate.getCode());
            newTemplate.setName(formTemplate.getName());
            newTemplate.setSystemId(formTemplate.getSystemId());
            newTemplate.setActive(1); //设置为可用
            newTemplate.setContent(template.getContent());
            newTemplate.setCreateBy(username);
            newTemplate.setUseId(0L);
            newTemplate.setUpdateTime(new Date());
            getBaseMapper().insert(newTemplate);
            //从最新表中删掉被编辑的数据
            getBaseMapper().deleteById(template.getId());
            //将其他历史模板的useId改成现在最新的模板的id
            formTemplate.setUseId(newTemplate.getId());
            formTemplate.setActive(0); //设置为不可用
            FormTemplateHistory formTemplateHistory = new FormTemplateHistory();
            BeanUtils.copyProperties(formTemplate, formTemplateHistory);
            formTemplateHistoryService.save(formTemplateHistory);
            formTemplateHistoryService.getBaseMapper().updateUseId(template.getId(), newTemplate.getId());
        }
        return ResponseResult.success();
    }

    public ResponseResult<FormTemplate> getByItemCode(String itemCode) {
        final ResponseResult<ItemData> result = itemClient.getByCode(itemCode);
        ItemData item = null;
        if (result != null)
            item = result.getData();
        FormTemplate formTemplate = null;
        if (item != null) {
            formTemplate = getBaseMapper().selectById(item.getTemplateId());
        }
        return ResponseResult.success(formTemplate);
    }

    public int getMaxVersion(Long id) {
        return getBaseMapper().getMaxVersion(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean changeVersion(Long oldId, Long newId) {
        FormTemplate oldTemplate = getBaseMapper().selectById(oldId);
        oldTemplate.setActive(0); //被弃用模板不可用
        oldTemplate.setUseId(newId);
        //先删掉旧数据
        getBaseMapper().deleteById(oldId);
        //先判断该数据在历史表中是否存在了，如果不存在数据插入，否则更新时间
        FormTemplateHistory formTemplateHistoryExist = formTemplateHistoryService.getBaseMapper().selectById(oldId);
        if (formTemplateHistoryExist == null) {
            FormTemplateHistory formTemplateHistory = new FormTemplateHistory();
            BeanUtils.copyProperties(oldTemplate, formTemplateHistory);
            formTemplateHistory.setUseId(newId);
            formTemplateHistory.setActive(0);
            formTemplateHistoryService.getBaseMapper().insert(formTemplateHistory);
        } else {
            formTemplateHistoryExist.setUseId(newId);
            formTemplateHistoryExist.setUpdateTime(new Date());
            formTemplateHistoryService.getBaseMapper().updateById(formTemplateHistoryExist);
        }

        //再查出即将成为新数据的历史数据,并且插入
        FormTemplateHistory formTemplateHistoryToNew = formTemplateHistoryService.getBaseMapper().selectById(newId);
        if (formTemplateHistoryToNew == null)
            return false;
        formTemplateHistoryToNew.setActive(1);
        formTemplateHistoryToNew.setUseId(0L);
        formTemplateHistoryToNew.setVersion(Math.max(getBaseMapper().getMaxVersion(oldTemplate.getId()) == null ? 0 : getBaseMapper().getMaxVersion(oldTemplate.getId()), formTemplateHistoryService.getBaseMapper().getMaxVersion(oldTemplate.getId()) == null ? 0 : formTemplateHistoryService.getBaseMapper().getMaxVersion(oldTemplate.getId())) + 1); // 获取最大版本+1
        formTemplateHistoryToNew.setId(null);
        FormTemplate formTemplate = new FormTemplate();
        BeanUtils.copyProperties(formTemplateHistoryToNew, formTemplate);
        getBaseMapper().insert(formTemplate);
        formTemplateHistoryService.getBaseMapper().updateUseId(oldId, formTemplate.getId());
        return true;
    }

    public int saveTemplate(FormTemplate formTemplate) {
        ResponseResult<SystemData> system = systemClient.getById(formTemplate.getSystemId());
        LambdaQueryWrapper<FormTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.likeRight(FormTemplate::getCode, system.getData().getCode() + "_");
        lqw.eq(FormTemplate::getUseId, 0);
        long count = getBaseMapper().selectCount(lqw);
        StringBuilder code = new StringBuilder();
        code.append(system.getData().getCode()).append("_").append("form_").append(String.format("%05d", count + 1));
        formTemplate.setCode(code.toString());
        return getBaseMapper().insert(formTemplate);
    }

    public List<FormTemplateData> getBySystemId(Long systemId) {
        Map<String, Object> params = new HashMap<>();
        params.put("system_id", systemId);
        List<FormTemplate> formTemplates = getBaseMapper().selectByMap(params);
        List<FormTemplateData> formTemplateDatas = new ArrayList<>();
        if (!CollectionUtils.isEmpty(formTemplates)) {
            for (FormTemplate formTemplate : formTemplates) {
                FormTemplateData formTemplateData = new FormTemplateData();
                BeanUtils.copyProperties(formTemplate, formTemplateData);
                formTemplateDatas.add(formTemplateData);
            }
        }
        return formTemplateDatas;
    }

    public ResponseResult<List<ItemData>> getItemByFormId(Long formTemplateId) {
        ResponseResult<List<ItemData>> items = itemClient.getItemByFormId(formTemplateId);
        if (items == null || items.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResponseResult.error("查询表单绑定的事项出错");
        }
        return ResponseResult.success(items.getData());
    }

}
